import React, {useEffect, useRef, forwardRef, useImperativeHandle, useState} from 'react';
import { Col,Select, Form, Button, message } from 'antd';
import PolicyCommonMent from './policyCommonMent';
import services from '../../../services/api';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import '../index.less'
const { Option } = Select;
function teps1(props,forwardedRef) {
  const [strategyCommon, setStrategyCommon] = useState([]);
  const [submitData, setSubmitData] = useState([]);
  const [stargyData, setStargyData] = useState({});
  const [showLeftBtn, setLeftBtn] = useState(false);
  const [showRightBtn, setRightBtn] = useState(false);
  const childNode = useRef(null);
  // useEffect(()=>{
  //   strategyComponent();
  // },[]);
  useEffect(() => {
    if (props.tabsClick === '2'  && Object.keys(props.requestParam).length) {
      props.form.setFieldsValue({strategy_ids: []});
      setSubmitData([]);
      strategyComponent();
      stargyHit([]); // 类型改了请求数据
    }
  },[props.stepType, props.grainType, props.requestParam, props.timeType, props.tabsClick]);
  // function handleChange(values) {
  //   setCodeList(values);
  // }
  useImperativeHandle(forwardedRef, () => ({
    downData
  }));
  // 组件选择
  function strategyComponent() {
    const params = {};
    if (props.echoParams) {
      params.report_id = props.echoParams.report_id
      params.send_time = props.echoParams.send_time
      params.token = props.echoParams.token
    }
    services[props.actionType].all({ 
       event_id: props.requestParam.event_id,
       product_id: props.requestParam.product_id,
       app_id: props.requestParam.app_id, ...params}).then(res => {
      if (!res.code) {
        setStrategyCommon(res.data);
      } else {
        message.error(res.msg);
      }
    })
  }
  // 获取参数
  function downData() {
    let params = getParamsData(submitData);
    return params;
  };
  function getParamsData(data) {
    let count = childNode.current.preveIndex;
    let isHideRight = false
    let strategy_ids = submitData;
    if (typeof data === 'number') {
      count = data;
      isHideRight = true;
    } else if (data && typeof data !== 'number') {
      strategy_ids = data;
      count = 0;
      childNode.current.setPreveFn();
    } else {
      count = 0;
      childNode.current.setPreveFn();
    }
    const times = childNode.current.getCurrentTime(props.timeType, count);
    if (!isHideRight || !count) {
      setRightBtn(false);
    } else if (isHideRight) {
      if (count) {
        setRightBtn(true);
      }
    }
    if (moment(times.current_start) >= moment(times.current_end)) {
      setLeftBtn(true);
    } else {
      setLeftBtn(false);
    }
    if (moment(times.current_start) >= moment(props.requestParam.start)) {
      setLeftBtn(true);
    } else {
      times.current_start = props.requestParam.start;
    };
    const params = {
      ...props.requestParam,
      level: props.stepType,
      strategy_ids: strategy_ids,
      type: props.timeType,
      // strategy_versions: [],
      strategy_type: 1,
      ...times
    }
    return params;
  };
  // 请求策略命中
  function stargyHit(data) {
    let params = getParamsData(data);
    services[props.actionType].strategyAnalysis(params).then(res => {
       if (!res.code) {
        const lits = reastData(cloneDeep(res.data));
        setStargyData(lits);
       } else {
         message.error(res.msg);
       }
    });
  };
  // 重置数据
  function reastData(data) {
    if (props.grainType === 'request' || !Object.keys(stargyData).length) return data;
    data.hit_ranking = data.hit_ranking.map(it => {
      it.value = (it.count && ((it.value / it.count) * 10000).toFixed() / 100) || 0;
      return it;
    });
    data.hit_trend = data.hit_trend.map(it => {
      it.value = it.value.map(item => {
          item.requests = (it.count && ((item.requests / it.count) * 10000).toFixed() / 100) || 0;
          return item;
       })
       return it;
    })
    return data;
  };
  function handleSumit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const lists = values.strategy_ids
        setSubmitData(lists);
        stargyHit(lists);
      }
    })
  };
  function nextFn(data) {
    stargyHit(data);
    if (!data) {
      setRightBtn(false);
    } else {
      setRightBtn(true);
    }
  };
  function changeValues(rule ,value , callback) {
    if (value.length > 5){
    　 callback('最多选择五条规则');
    } else {
    　 callback();
    }
  };
  const components = (<Form
    name="customized_form_controls"
    layout="inline"
    className='select-max'
    onSubmit={() => false}
  >
    <Form.Item name="price" label="组件名称">
    {props.form.getFieldDecorator('strategy_ids', {
      initialValue: undefined,
      rules: [{validator : changeValues}]
    })(
      <Select 
        mode="multiple" 
        style={{ width: '300px' }} 
        placeholder="请选择组件"
        showArrow={true}
        // defaultValue={codeList}
        // onChange={handleChange}
      >
         {strategyCommon.map(item => {
            return (<Option key={item.strategy_id} value={item.strategy_id}>{item.name}</Option>)
          })
         }
      </Select>)
      }
    </Form.Item>
    <Form.Item>
      <Button type="primary" onClick={handleSumit}>
        确定
      </Button>
    </Form.Item>
  </Form>)
  const renders = (record, index) => {
    return (
      <>
        <span style={{ marginRight: '10px' }}>{index + 1}</span>
        {record.name}
      </>
    );
  }
  return (
    <>
      <Col key={1} span={24}>
        <PolicyCommonMent
          {...props}
          ref={childNode}
          showLeftBtn={showLeftBtn}
          showRightBtn={showRightBtn}
          nextFn={nextFn}
          lineTitle='组件命中趋势'
          progressTitle='组件命中排名'
          component={components}
          trendList={stargyData.hit_trend || []}
          leftLabel='组件'
          rightLabel={props.grainType === 'request' ? '命中次数' : '命中比率'}
          keyValue={['key', 'value']}
          dataSource={stargyData.hit_ranking || []}
          total={props.grainType === 'request' ? ((stargyData.hit_ranking && stargyData.hit_ranking.length) ? stargyData.hit_ranking[0].count : 100) : 100}
          renderLabel={renders}
          renderValue= {(record, index) => {
            return props.grainType=== 'request' ? record.value : (record.value +'%')
            }
          }
        ></PolicyCommonMent>
      </Col>
    </>
  )
}
export default forwardRef(teps1)